package com.qdxwx.web.utils;

import com.qdxwx.common.constants.CacheConstants;
import com.qdxwx.common.utils.TKCookie;
import com.qdxwx.models.company.Company;
import com.qdxwx.models.user.User;
import com.qdxwx.models.user.UserToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

/**
 * @author developer
 *
 */
public class LoginUser {

	private static final Logger logger = LoggerFactory.getLogger(LoginUser.class);

	public static Company getCompany(HttpServletRequest request) {
		return (Company) request.getAttribute("siteCompany");
	}

	public static int getCompanyId(HttpServletRequest request) {
		Company company = getCompany(request);
		if (company == null) {
			return 0;
		}
		return company.getCompanyId();
	}
	/**
	 * 获取前台登录用户ID
	 *
	 * @param request
	 * @return 返回用户ID
	 */
	public static long getUserId(HttpServletRequest request) {
		User user = getUser(request);
		if (user != null) {
			return user.getUserId();
		}
		return 0;
	}

	/**
	 * 获取前台登录用户
	 *
	 * @param request
	 * @return User
	 */
	public static User getUser(HttpServletRequest request) {
		return (User) request.getSession().getAttribute("login-user");
	}

	/**
	 * 写入登录信息
	 * @param user
	 * @return
	 */
	public static void setUser(HttpServletRequest request, User user) {
		setUser(request.getSession(), user);
	}

	public static void setUser(HttpSession session, User user) {
		session.setAttribute("login-user", user);
		session.setMaxInactiveInterval(1800);
	}

	public static void setCookie(HttpServletResponse response, UserToken token){
		//用户的token写入Cookies
		TKCookie.set(response, CacheConstants.USER_LOGIN_COOKIE_NAME, token.getUserId() + "|" + token.getToken(), CacheConstants.USER_LOGIN_COOKIE_DAYS);
	}

	public static String getCookie(HttpServletRequest request) {
		//用户的token写入Cookies
		return TKCookie.get(request, CacheConstants.USER_LOGIN_COOKIE_NAME);
	}

	public static void removeCookie(HttpServletResponse response) {
		TKCookie.delete(response, CacheConstants.USER_LOGIN_COOKIE_NAME);
	}

	public static void removeUser(HttpSession session) {
		session.removeAttribute("login-user");
		session.invalidate();
	}
}
